Angular Custom Directives

In this article you will learn how to create a custom directive in angular and reuse it across our application

Directives are used to attach custom behavior to the elements in the DOM. In this article we can create a custom directive and provide some custom behavior to the directive using HostBinding and HostListener.

HostBinding is used to set properties of the element. You can bind to any property or style or class or to an attribute using HostBinding. Below are few ways of using HostBinding.

@HostBinding('disabled')

@HostBinding('style.backgroundColor')

@HostBinding('class.highlight')

@HostBinding('attr.role')

HostListener is used to listen for events on the host element. Let's see it with an example.

Create a directive using angular cli command

ng g d directives/highlight

This will create a custom directive in directives folder. Also confirm that the directive has been referred in the app.module.ts.

Now modify the default coding with

import { Directive } from '@angular/core';
import { HostBinding, HostListener } from '@angular/core';
@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  hoverColor = 'yellow';
  @HostBinding('style.backgroundColor') backgroundColor: string;

  constructor() { }

  @HostListener('mouseover') mouseOver() {
    this.backgroundColor = this.hoverColor;
  }

  @HostListener('mouseout') mouseOut() {
    this.backgroundColor = 'transparent';
  }
}

In the above code we had imported HostBinding and HostListener.

Next, we shall bind to background-color property of the element. For binding we used

@HostBinding('style.backgroundColor') backgroundColor: string;

We have used style.backgroundColor instead of background-color since we are accessing DOM properties. This will get a string as value which will be the background color of the element.

As mentioned above HostListener is used to listen for events on the host element. Here we created 2 events using HostListener decorator.

  • Mouseover
  • Mouseout

Whenever the mouse is hovered over the element to which the custom directive is applied then, mouseover will be called which in turns changes the backgroundColor to yellow color. On mouseout event, the backgroundColor will be set to transparent.

To apply this custom directive to an element of any component then provide the selector of directive which is appHighlight to the element like below.

<p appHighlight>Welcome to Readersbuddy</p>

If you run the application and hover on Welcome to Readersbuddy, it will set the background color to yellow and if you remove the focus from it, then it will remove the background color.


Most Read